//
//  SYShoppingViewController.m
//  Term Of Section B
//
//  Created by 韩震明 on 15/11/27.
//  Copyright © 2015年 韩震明. All rights reserved.
//

#import "SYShoppingViewController.h"  // 主界面控制器
#import "SYMainTableViewCell.h"  // 第一个TableViewCell
#import "SYNextTableViewCell.h"  // 第二个TableViewCell
#import "SYMainTableViewModel.h"  // TableView中第一个分区的Model
#import "SYNextTableViewModel.h"  // TableView中第二个分区的Model
#import "SYSearchJumpViewController.h"  // 跳转界面
#import "SYSecondViewController.h"  // 第一个TableViewCell中CollectionView要跳转的界面
#import "SYThirdViewController.h"  // 第二个TableViewCell中的跳转


// 4.签订协议
@interface SYShoppingViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, SYMainTableViewCellDelegate>

@property (nonatomic, strong) SYBaseTableView *mainTableView;  // 主界面的TableView

@property (nonatomic, strong) NSMutableArray *mainArray;  // 第一个分区装数据的数组

@property (nonatomic, strong) NSMutableArray *nextArray;  // 第二个分区装数据的数组

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSString *string;

@end

@implementation SYShoppingViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    [self createMainTableView];
    
    [self createSearchBar];
    
    [self createMainData];
    
    [self createNextData];
    
}

// 创建搜索条
- (void) createSearchBar {
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(100, 20, 200, 0)];
    [self.navigationController.navigationBar addSubview:self.searchBar];
    self.searchBar.placeholder = @"搜索物品";
    [self.searchBar setShowsCancelButton:YES];
    self.searchBar.delegate = self;
    
}

// 点击取消
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.searchBar resignFirstResponder];
}

// 允许开始编辑
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    return YES;
}

// 允许结束编辑
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    return YES;
}

// 结束编辑
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    NSLog(@"%@", searchBar.text);
}

// 开始编辑
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    
}

// 实时搜索
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
}

// 点确定 点搜索走此方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    self.string = [searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSLog(@"%@", self.string);
    
    SYSearchJumpViewController *searchJumpVC = [[SYSearchJumpViewController alloc] init];
    [self.navigationController pushViewController:searchJumpVC animated:YES];
    
    searchJumpVC.searchText = searchBar.text;
    searchJumpVC.string = self.string;
    self.searchBar.text = @"";
    [self.searchBar resignFirstResponder];  // 跳到下一个界面的时候让searchBar失去第一响应者是为了让键盘回收

}

- (void)viewWillAppear:(BOOL)animated {
    self.searchBar.hidden = NO;
    self.searchBar.text = @"";
}

// 创建主界面TableView
- (void)createMainTableView {

    self.mainTableView = [[SYBaseTableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self.view addSubview:self.mainTableView];
    
    self.mainTableView.dataSource = self;
    self.mainTableView.delegate = self;
    
}

// 6.实现协议方法
- (void)pushIndexID:(NSString *)indexID withName:(NSString *)name {
    SYSecondViewController *secondVC = [[SYSecondViewController alloc] init];
    [self.navigationController pushViewController:secondVC animated:YES];
    secondVC.indexID = (NSNumber *)indexID;
    secondVC.name = name;
}

// TableViewCell的方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 当索引分区等于第一个分区的时候
    if (indexPath.section == 0) {
        self.mainTableView.rowHeight = 250;
        static NSString *reuse = @"reuse";
        SYMainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[SYMainTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
        };
        
        // 5.设置代理人
        cell.delegate = self;
        
        // 传值
        cell.mainArray = self.mainArray;
        
        // 刷新collectionView中的数据
        [cell.mainCollectionView reloadData];
        
        // 当选择某个cell时的颜色
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
        
    } else {
        
        // 当索引分区等于其他分区的时候.
        self.mainTableView.rowHeight = 180;
        static NSString *reuse = @"newReuse";
        SYNextTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[SYNextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
        }
        
        SYNextTableViewModel *unde = self.nextArray[indexPath.row];
        cell.leftAddLabel.text = unde.brand;
        cell.leftProductLabel.text = unde.productDescription;
        [cell.leftImage sd_setImageWithURL:[NSURL URLWithString:unde.image] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
}

// TableView中,每个分区有几行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else {
        return self.nextArray.count;
    }
}

// TableView中,有几个分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

// 设置某个分区的头视图高度
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    } else {
        return 40;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
    headerView.backgroundColor = [UIColor whiteColor];
    
    
    UILabel *middleLabel = [[UILabel alloc] initWithFrame:CGRectMake(130, 0, 100, 40)];
    middleLabel.backgroundColor = [UIColor whiteColor];
    middleLabel.text = @"精     选";
    middleLabel.textAlignment = NSTextAlignmentCenter;
    [headerView addSubview:middleLabel];
    
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(50, 20, 70, 1)];
    leftView.backgroundColor = [UIColor blackColor];
    [headerView addSubview:leftView];
    
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(240, 20, 70, 1)];
    rightView.backgroundColor = [UIColor blackColor];
    [headerView addSubview:rightView];
    
    return headerView;
}

// TableView中第二个分区的跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SYThirdViewController *third = [[SYThirdViewController alloc] init];
    [self.navigationController pushViewController:third animated:YES];
    
    SYNextTableViewModel *model = self.nextArray[indexPath.row];
    NSString *string = [NSString stringWithFormat:@"%@", model.productID];
    
    third.interID = string;
    
}

// 解析第一个分区中的数据
- (void)createMainData {
    
    NSString *str = @"http://api.xiangqu.com/category/out/children";
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"post"];
    NSString *bodyStr = @"key=e1829c7ad984809a9290e1a3a3b1f4ff&t=1445821154795";
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        self.mainArray = [NSMutableArray array];
        self.mainArray = [SYMainTableViewModel baseModelByArr:dic[@"data"]];
        [self.mainTableView reloadData];
        
    }];
    
}

// 解析第二个分区中的数据
- (void)createNextData {
    
    NSString *str = @"http://api.xiangqu.com/search/list";
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"post"];
    NSString *bobyStr = @"key=d5d8ff390a807ba8513f21c45f4fb5cb&page=0&t=1445862694849&userid=705811";
    NSData *bodyData = [bobyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        self.nextArray = [NSMutableArray array];
        self.nextArray = [SYNextTableViewModel baseModelByArr:dic[@"data"][@"records"]];
        
        [self.mainTableView reloadData];
    }];
    
}

//- (void)footerAction {
//    self.page = 0;
//    self.page++;
//    NSString *str = @"http://api.xiangqu.com/search/list";
//    NSURL *url = [NSURL URLWithString:str];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//    [request setHTTPMethod:@"POST"];
//    NSString *bodyStr = [NSString stringWithFormat:@"key=d5d8ff390a807ba8513f21c45f4fb5cb&page=%ld&t=1445862694849&userid=705811", self.page];
//    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
//    [request setHTTPBody:bodyData];
//    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//        
//        NSMutableArray *arArr = [NSMutableArray array];
//        arArr = [CLunder baseModelByArr:dic[@"data"][@"records"]];
//        for (CLunder *under in arArr) {
//            [self.liArr addObject:under];
//        }
//        
//        [self.liArr removeLastObject];
//        [self.mainTableView.footer endRefreshing];
//        [self.mainTableView reloadData];
//        
//    }];
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
